/**
 * 
 */
package org.gov.vis.data.gui.listener;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.ResourceBundle;

import javax.swing.JOptionPane;

import org.gov.vis.common.exceptions.InvalidInputException;
import org.gov.vis.data.controller.DistributionLnCtlr;
import org.gov.vis.data.controller.DistributionLnCtlrImpl;
import org.gov.vis.data.dto.DistributionLnDto;
import org.gov.vis.data.gui.EditDistributionLNDialog;
import org.gov.vis.data.gui.ViewDistributionLNDialog;
import org.gov.vis.gui.util.ErrorsDisplayJPanel;
import org.gov.vis.main.Main;
import org.gov.vis.master.gui.listener.BaseListener;
import org.gov.vis.util.GuiConstants;
import org.gov.vis.util.Util;
import org.gov.vis.util.ValidatorUtils;

/**
 * @author user
 *
 */
public class EditDistributionLNListener implements ActionListener,BaseListener,FocusListener{



	final private ResourceBundle rb = Util.getResources();

	private DistributionLnCtlr distributionLNCtlr = new DistributionLnCtlrImpl();

	private EditDistributionLNDialog editDistributionLNDialog;

	private ErrorsDisplayJPanel errorMsgPanel;

	private DistributionLnDto distributionLnDto;

	public EditDistributionLNListener(EditDistributionLNDialog editDistributionLNDialog) {
		// TODO Auto-generated constructor stub
		this.editDistributionLNDialog = editDistributionLNDialog;
	}

	@Override
	public void clear() {
		// TODO Auto-generated method stub

	}

	@Override
	public void setGuiDetailsToDto(Object _guiObject) {
		EditDistributionLNDialog _editDistributionLNDialog = (EditDistributionLNDialog)_guiObject;
		distributionLnDto = new DistributionLnDto();
		distributionLnDto.setCode(_editDistributionLNDialog.getTxtFldCode().getText());
		distributionLnDto.setCnvtdLtrs(_editDistributionLNDialog.getTxtFldDLNConvertedLtrs().getText());
		//distributionLnDto.setDoDstrbut(DU.parse(_distributionLNDialog.getTxtFldDLNDODistribution().getText()));
		if(_editDistributionLNDialog.getDtChoDateOfDistribution().getDate() != null){
			distributionLnDto.setDoDstrbut(_editDistributionLNDialog.getDtChoDateOfDistribution().getDate());
		}

		distributionLnDto.setEvopLoss(_editDistributionLNDialog.getTxtFldDLNEvoporation().getText());
		distributionLnDto.setFrmStation(_editDistributionLNDialog.getTxtFldDLNFromStation().getText());
		distributionLnDto.setKgs(_editDistributionLNDialog.getTxtFldDLNKgs().getText());
		distributionLnDto.setVehicleNo(_editDistributionLNDialog.getTxtFldDLNVehicalNo().getText());
		distributionLnDto.setDisLnId((Long)_editDistributionLNDialog.getHidnObject());


	}

	@Override
	public void setDtoDetailsToGui(Object _dtoObject) {
		// TODO Auto-generated method stub

	}

	@Override
	public void clearGUILabelColors(Color _labelColor) {
		// TODO Auto-generated method stub

	}

	@Override
	public void actionPerformed(ActionEvent actionEvent) {
		// TODO Auto-generated method stub

		errorMsgPanel = new ErrorsDisplayJPanel(editDistributionLNDialog.getjPanel1());
		errorMsgPanel.clearMsgPanel();


		if(actionEvent.getActionCommand().equals(rb.getString("dialog_button_update"))){

			//Method called to either Add or Edit the GopalaMithra details
			addOrEditDistributionLN();
		}

		if(actionEvent.getActionCommand().equals(rb.getString("dialog_button_delete"))){
			
			int response = JOptionPane.showConfirmDialog(null, GuiConstants.DELETE_CONFIRM_MSG, "Confirm",
			        JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
			    
		    if (response == JOptionPane.YES_OPTION) {
		      // User clicked YES.
		    	deleteDistributionLN(actionEvent);
		    	String searchText = editDistributionLNDialog.getSearchText();

				// It is basically doing back button functionality. Please, understand the logic and write the comments.
				//Replace double quotes with appropriate Dialog title.
				ViewDistributionLNDialog viewDistLnDialog = new ViewDistributionLNDialog(Main.getMainFrame(), "View Distribution LN", false);
				for(ActionListener actionListener: viewDistLnDialog.getSearchBtn().getActionListeners()) { 
					ViewDistributionLNListener viewDistLnList = (ViewDistributionLNListener)actionListener;
					viewDistLnDialog.getCodeTxtBx().setText(searchText);

					viewDistLnList.actionPerformed(new ActionEvent(viewDistLnDialog.getSearchBtn(), 1, rb.getString("dialog_button_serach")));
				}


		    	
		    } else if (response == JOptionPane.NO_OPTION || response == JOptionPane.CLOSED_OPTION) {
		      return;
		    }

		}
	}

	private void addOrEditDistributionLN() {

		//Method called to set the Field's Labels to default Black color
		clearGUILabelColors(blackColor);

		//Method to set the Screen's data to  the DTO Object
		setGuiDetailsToDto(editDistributionLNDialog);

		try{
			//Method called to Add or Edit the GopalaMithra
			distributionLNCtlr.addOrEditDisLN(distributionLnDto);

			JOptionPane.showMessageDialog(editDistributionLNDialog, rb.getString(GuiConstants.DATA_EDIT_DISTRBUTIONLN_SUCCESS));
			editDistributionLNDialog.dispose();
			
			String searchText = editDistributionLNDialog.getSearchText();

			// It is basically doing back button functionality. Please, understand the logic and write the comments.
			//Replace double quotes with appropriate Dialog title.
			ViewDistributionLNDialog viewDistLnDialog = new ViewDistributionLNDialog(Main.getMainFrame(), "View Distribution LN", false);
			for(ActionListener actionListener: viewDistLnDialog.getSearchBtn().getActionListeners()) { 
				ViewDistributionLNListener viewDistLnList = (ViewDistributionLNListener)actionListener;
				viewDistLnDialog.getCodeTxtBx().setText(searchText);

				viewDistLnList.actionPerformed(new ActionEvent(viewDistLnDialog.getSearchBtn(), 1, rb.getString("dialog_button_serach")));
			}

		}catch(Exception e){
			List<String> errorMsgLst = new ArrayList<String>();
			if(e instanceof InvalidInputException){
				final HashMap<String,String> _exceptions = DistributionLnCtlr.errorMsgs;
				if (_exceptions != null && !_exceptions.isEmpty()) {
					String errMsg = null;
					if(_exceptions.containsKey(rb.getString("dialog_label_dist_ln_code").toUpperCase())){
						editDistributionLNDialog.getLblCode().setForeground(redColor);
						errMsg = _exceptions.remove(rb.getString("dialog_label_dist_ln_code").toUpperCase());
						errorMsgLst.add(errMsg);
					}
					if(_exceptions.containsKey(rb.getString("dialog_label_dist_ln_dtofdstr").toUpperCase())){
						editDistributionLNDialog.getLblDateOfDistribution().setForeground(redColor);
						errMsg = _exceptions.remove(rb.getString("dialog_label_dist_ln_dtofdstr").toUpperCase());
						errorMsgLst.add(errMsg);
					}
					if(_exceptions.containsKey(rb.getString("dialog_label_dist_ln_frmstation").toUpperCase())){
						editDistributionLNDialog.getLblFromStation().setForeground(redColor);
						errMsg = _exceptions.remove(rb.getString("dialog_label_dist_ln_frmstation").toUpperCase());
						errorMsgLst.add(errMsg);
					}

					if(_exceptions.containsKey(rb.getString("dialog_label_dist_ln_vehiceno").toUpperCase())){
						editDistributionLNDialog.getLblVehicalNo().setForeground(redColor);
						errMsg = _exceptions.remove(rb.getString("dialog_label_dist_ln_vehiceno").toUpperCase());
						errorMsgLst.add(errMsg);
					}
					if(_exceptions.containsKey(rb.getString("dialog_label_dist_ln_kgs").toUpperCase())){
						editDistributionLNDialog.getLblKgs().setForeground(redColor);
						errMsg = _exceptions.remove(rb.getString("dialog_label_dist_ln_kgs").toUpperCase());
						errorMsgLst.add(errMsg);
					}

					errorMsgPanel.setErrorMessages(errorMsgLst);
				} else {
					//log.debug(e.getMessage(), e);
				}	
			}
			else{
				errorMsgLst.add(e.getMessage());
				errorMsgPanel.setErrorMessages(errorMsgLst);

			}
		}		


	}

	private void deleteDistributionLN(ActionEvent actionEvent) {

		Long distributionLNsId = (Long)editDistributionLNDialog.getHidnObject();
		try {
			distributionLNCtlr.deleteDisLN(distributionLNsId);
			JOptionPane.showMessageDialog(editDistributionLNDialog, rb.getString(GuiConstants.DATA_DELETE_DISTRBUTIONLN_SUCCESS));
			editDistributionLNDialog.dispose();
		} catch (Exception e) {
			List<String> errorMsgLst = new ArrayList<String>();
			errorMsgLst.add(e.getMessage());
			errorMsgPanel.setErrorMessages(errorMsgLst);

		}
	}


	@Override
	public void focusGained(FocusEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void focusLost(FocusEvent arg0) {
		// TODO Auto-generated method stub
		errorMsgPanel = new ErrorsDisplayJPanel(editDistributionLNDialog.getjPanel1());
		errorMsgPanel.clearMsgPanel();
		clearGUILabelColors(blackColor);

		convertKgsToLitters();
	}	
	private void convertKgsToLitters() {
		// TODO Auto-generated method stub
		HashMap<String, String> errorMsgs = new HashMap<String, String>();
		List<String> errorMsgLst = new ArrayList<String>();
		try{
			String _disLNKgsErr = ValidatorUtils.validateDecimal(rb.getString("dialog_label_dist_ln_kgs"),editDistributionLNDialog.getTxtFldDLNKgs().getText() , ValidatorUtils.DECIMALS, 0, Double.MAX_VALUE, 0, 2, false, false);
			if(_disLNKgsErr != null)
				errorMsgs.put(rb.getString("dialog_label_dist_ln_kgs").toUpperCase(), _disLNKgsErr);
			if (errorMsgs != null && !errorMsgs.isEmpty())
				throw new InvalidInputException();
			double kgs = Double.parseDouble(editDistributionLNDialog.getTxtFldDLNKgs().getText());
			double litters = kgs * 1.078;
			editDistributionLNDialog.getTxtFldDLNConvertedLtrs().setText(String.valueOf(litters));


		}catch(InvalidInputException iie){
			String errMsg = null;
			if(errorMsgs.containsKey(rb.getString("dialog_label_dist_ln_kgs").toUpperCase())){
				editDistributionLNDialog.getLblKgs().setForeground(redColor);
				errMsg = errorMsgs.remove(rb.getString("dialog_label_dist_ln_kgs").toUpperCase());
				errorMsgLst.add(errMsg);
			}

			errorMsgPanel.setErrorMessages(errorMsgLst);

		}
	}



}
